package br.ucb.sispro.persistencia;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import br.ucb.sispro.model.Entity;

public class GenericDAO <E extends Entity> implements IGenericDAO<E> {

	private HibernateTemplate hibernateTemplate;

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	@Override
	public long save(E entity) {
		return (Long) hibernateTemplate.save(entity);
	}

	@Override
	public void update(E entity) {
		hibernateTemplate.update(entity);
	}
	
	
	@SuppressWarnings("unchecked")
	public E load(String entity,long id){
		return (E) hibernateTemplate.load(entity, id);
	}

	@Override
	public void delete(E entity) {
		hibernateTemplate.delete(entity);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<E> findByCriteria(E entity, String value) {
		DetachedCriteria criteria  = DetachedCriteria.forClass(entity.getClass()).add
		(Restrictions.like(entity.getSearchComlumnEntity(),"%"+value+"%"));
		return hibernateTemplate.findByCriteria(criteria);
	}

	@SuppressWarnings("unchecked")
	public List<E> findByHQLLivre(Entity entity,String campoPesquisa, String value) {
		String hql = "from " + entity.getClass().getSimpleName() + "  where   "  + campoPesquisa+   "   like '%"+value+"%'";
		return hibernateTemplate.find(hql);
		
	}
	
	
	public List<E> findByHQL(Entity entity,String campoPesquisa, String value) {
		String hql = "from " + entity.getClass().getSimpleName() + "  where   "  + campoPesquisa+   "= '"+value+"'";
		return hibernateTemplate.find(hql);
		
	}	
	
	
	
	public List<E> findSenhaByUser(Entity entity, String senha,String user) {
		String hql = "from " + entity.getClass().getSimpleName() + "  where  login = '"+user+"' and senha = '"+senha+"'";
		return hibernateTemplate.find(hql);
		
	}	
	
	
	
	
	
	
	@SuppressWarnings("unchecked")
	@Override
	public List<E> findByHQL(E entity, String value) {
		String hql = "from " + entity.getClass().getSimpleName() + "where" + entity.getSearchComlumnTable()+"like '%"+value+"%'";
		return hibernateTemplate.find(hql);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<E> getList(E entity) {
		return (List<E>) hibernateTemplate.loadAll(entity.getClass());
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<E> findByNamedQuery(String query,String valor) {
		return hibernateTemplate.findByNamedQuery(query, valor);
	}
	public boolean verificaFuncao(String apelidoFuncao,long codUsuario){
		String hql = "from  FuncaoComputacional  where funcao = '"+ apelidoFuncao + "' and TipoUsuario_idTipoUsuario = "+ codUsuario;
		if(hibernateTemplate.find(hql).size()!=0){
			return true;
		}
		return false;
	}
}
